<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>矩形直线动画(关键帧)</title>
</head>
<body style="margin: 0;padding: 0;" onload="draw()">
<canvas id="canvas" width="800px" height="400px" style="border: solid 1px #000;"></canvas>
<script>
function draw(){
  let canvas = document.querySelector("#canvas");
  if(canvas.getContext){
    //创建context对象
    let cvsCtx = canvas.getContext("2d");
    //1.绘制图像
    //2.清除画布
    //3.更新位置
    //4.绘制图像 2. 3. 4.
    //面向对象
    function Rect(x,y,width,height,color,speedX,speedY){
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
      this.color = color;
      this.speedX = speedX;
      this.speedY = speedY;
    }
    Rect.prototype.draw = function(){
      cvsCtx.beginPath();
      cvsCtx.fillStyle = this.color;
      cvsCtx.fillRect(this.x, this.y, this.width, this.height);
    } 
    Rect.prototype.move = function(){
      
      //更新位置
      this.x += this.speedX;
      if(this.x > canvas.width-this.width || this.x < 0){
        this.speedX *= -1;
      }
      this.y += this.speedY;
      if(this.y > canvas.height-this.height || this.y < 0){
        this.speedY *= -1;
      }

    }
    function init(){
      //清除画布
      cvsCtx.clearRect(0, 0, canvas.width, canvas.height);
      rect1.draw();
      rect1.move();
      rect2.draw();
      rect2.move();
      //请求关键帧动画
      window.requestAnimationFrame(init);
    }  
    let rect1 = new Rect(0,0,50,50,'pink',5,5);
    let rect2 = new Rect(750,350,50,50,'skyblue',5,5);
    init();
    /* 面向过程 */
   /*  let x = 0,y = 0,width = 50,height = 50;
    cvsCtx.beginPath();
    cvsCtx.fillStyle = "pink";
    cvsCtx.fillRect(x, y, width, height);
    let speedX = 2,speedY = 2;
    // 1 请求关键帧动画（自动规划最优动画，不会失帧）
    function move(){
      //清除画布
      cvsCtx.clearRect(x, y, canvas.width, canvas.height);
      //更新位置
      x += speedX;
      if(x > canvas.width-width || x < 0){
        speedX *= -1;
      }
      y += speedY;
      if(y > canvas.height-height || y < 0){
        speedY *= -1;
      }
      //绘制图像
      cvsCtx.fillRect(x, y, width, height);
      //请求关键帧动画
      window.requestAnimationFrame(move);
    }
      move();
      //2 setInterval
    // setInterval(function(){
    //   //清除画布
    //   cvsCtx.clearRect(x, y, canvas.width, canvas.height);
    //   //更新位置
    //   x += speedX;
    //   if(x > canvas.width-width || x < 0){
    //     speedX *= -1;
    //   }
    //   y += speedY;
    //   if(y > canvas.height-height || y < 0){
    //     speedY *= -1;
    //   }
    //   cvsCtx.fillRect(x, y, width, height);
    // },5) */
  }
}
</script>
</body>
</html>